<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Supervisor;

class TwowayChoiceController extends Controller
{

    public function index() {
        $user = \Auth::user();
        $student = $user->student;
        $selectedSupervisors = $student->supervisors;
        $selectedSupervisors = $student->supervisors;
        foreach ($selectedSupervisors as $supervisor) {
            $supervisor->residue = $supervisor->quota - $supervisor->students()->wherePivot('isApproved', true)->count();
        }
        return view('student.twowaychoiceresult', compact("selectedSupervisors", "user"));
    }

    public function create()
    {
    	$user = \Auth::user();
    	$student = $user->student;
    	$isApproved = $student->supervisors()->wherePivot('isApproved', true)->count();
    	if ($isApproved) {
    		return Redirect::to('student/twowaychoice');
    	}
    	$selectedSupervisors = $student->supervisors;
    	$supervisors = Supervisor::all();
        foreach ($supervisors as $supervisor) {
            $supervisor->residue = $supervisor->quota - $supervisor->students()->wherePivot('isApproved', true)->count();
        }
    	return view('student.twowaychoice', compact("supervisors", "selectedSupervisors", "user"));
    }

    public function store(Request $request)
    {
    	$user = \Auth::user();
    	$student = $user->student;
    	$isApproved = $student->supervisors()->wherePivot('isApproved', true)->count();
    	if ($isApproved) {
    		return Redirect::to('student/twowaychoice');
    	}
  		$supervisor_ids = $request->input('supervisor');

  		$sync = Array();
        if (is_array($supervisor_ids)) {
      		foreach ($supervisor_ids as $supervisor_id) {
      			$sync[$supervisor_id] = array("isApproved" =>false);
      		}
        }
    	$student->supervisors()->sync($sync);
    	return Redirect::to('student/twowaychoice');
    }

}
